package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		// 获取商品id
		CreateOrderContext orderContext = (CreateOrderContext) context;
		List<CartProductDto> productDtoList = orderContext.getCartProductDtoList();
		List<Long> productIds = orderContext.getBuyProductIds();
		// 根据商品id获取库存信息
		List<Stock> stocks = stockMapper.findStocksForUpdate(productIds);
		// 校验
		if (stocks == null || stocks.isEmpty()) {
			throw new BizException(OrderRetCode.STOCK_NOT_INIT.getCode(),
					OrderRetCode.STOCK_NOT_INIT.getMessage());
		}
		ArrayList<CartProductDto> verifiedList = new ArrayList<>(productDtoList);
		stocks.forEach(stock -> {
			Iterator<CartProductDto> iterator = verifiedList.iterator();
			while (iterator.hasNext()) {
				CartProductDto productDto = iterator.next();
				if (stock.getItemId().equals(productDto.getProductId())) {
					iterator.remove();
				}
			}
		});
		if (!verifiedList.isEmpty()) {
			throw new BizException(OrderRetCode.STOCK_PART_NOT_INIT.getCode(),
					OrderRetCode.STOCK_PART_NOT_INIT.getMessage() + verifiedList.toString());
		}
		// 比较库存
		for (Stock stock : stocks) {
			for (CartProductDto productDto : productDtoList) {
				if (stock.getItemId().equals(productDto.getProductId())) {
					if (stock.getStockCount() < productDto.getProductNum()) {
						throw new BizException(OrderRetCode.STOCK_UNDER.getCode(),
								OrderRetCode.STOCK_UNDER.getMessage());
					}
					// 此时库存充足
					stock.setStockCount(-productDto.getProductNum());
					stock.setLockCount(productDto.getProductNum().intValue());
					// 更新
					stockMapper.updateStock(stock);
				}
			}
		}

		return true;
	}
}